#!/usr/bin/env python3
# encoding=utf-8

import os
import shutil
import with_win32 as wwin32
from threading import get_ident
from stat import S_IRUSR, S_IWUSR
from concurrent.futures  import ThreadPoolExecutor, ProcessPoolExecutor
from excel_by_openpyxl import filter_emailinfo_by_openpyxl, duil_with_file_by_openpyxl
from excel_by_win32 import duil_with_file_by_win32
from excel_by_xlwings import filter_emailinfo_by_xlwings, duil_with_file_by_xlwrings
from commom_api import (get_max_worker, get_temp_dirpath, get_doc_dirpath
                        , email_merge_by_product, get_excel_name_by_emailinfo)

import logging
logger = logging.getLogger(__name__)

def file_list_rename(filechlist):
    if len(filechlist) == 0:
        return
    for orgname, newname in filechlist.items():
        if not os.path.exists(orgname):
            continue
        shutil.copyfile(orgname, newname)
        os.chmod(newname, S_IRUSR)
        try:
            os.remove(orgname)
        except Exception as e:
            logging.error(f"rename remove error[{e}] {orgname}")
        
        orgname = os.path.join(os.path.dirname(orgname), os.path.basename(orgname).replace('净值表', '产品周报'))
        newname = os.path.join(os.path.dirname(newname), os.path.basename(newname).replace('净值表', '产品周报'))
        orgjpg = orgname.replace('.xlsx', '.jpg')
        newjpg = newname.replace('.xlsx', '.jpg')
        if os.path.exists(orgjpg):
            os.rename(orgjpg, newjpg)
        orgdoc = orgname.replace('.xlsx', '.docx')
        newdoc = newname.replace('.xlsx', '.docx')
        # print(f'{orgdoc} \n{newdoc}')
        if os.path.exists(orgdoc):
            os.rename(orgdoc, newdoc)

def remove_all_temp_file():
    tempdir = get_temp_dirpath()
    files = os.listdir(tempdir)
    for file in files:
        os.chmod(os.path.join(tempdir, file), S_IWUSR)
        os.remove(os.path.join(tempdir, file))

def duil_with_one_file(allparam):
    xlsname, maillist, codeinfo = allparam
    # olddate = find_origin_excel_date(xlsname)
    orgexcel = os.path.join(get_doc_dirpath(), xlsname)
    excelpath = os.path.join(get_temp_dirpath(), xlsname)
    if not os.path.exists(excelpath):
        shutil.copyfile(orgexcel, excelpath)
    curtid = get_ident()
    logger.info(f"excel {xlsname} tid {curtid}")
    wwin32.win32_com_init(curtid)
    # renamefile = duil_with_file_by_win32(excelpath, maillist, codeinfo)
    # renamefile = duil_with_file_by_openpyxl(excelpath, maillist, codeinfo)
    renamefile = duil_with_file_by_xlwrings(excelpath, maillist, codeinfo)
    file_list_rename(renamefile)
    # return renamefile[xlsinfo['excel']]

def fill_excel_with_code_value(emailinfo, codeinfo):
    if len(emailinfo) == 0 or len(codeinfo) == 0:
        return None
    emaildictinfo = email_merge_by_product(emailinfo)
    wwin32.check_all_process()
    taskparamlist = []
    for key, maillist in emaildictinfo.items():
        xlslist = get_excel_name_by_emailinfo( key, withspcode=(maillist[0]['code'], maillist[0]['name']) )
        for xlsname in xlslist:
            if xlsname == None:
                continue
            taskparamlist.append((xlsname, maillist, codeinfo))

    # with ProcessPoolExecutor(max_workers=get_max_worker()) as executor: # 从多线程改用多进程，无效
    with ThreadPoolExecutor(max_workers=get_max_worker()) as executor:
        futures = list(executor.map(duil_with_one_file, taskparamlist))
    # # 按完成顺序处理任务
    # for future in as_completed(futures):
    #     print(f"Result: {future.result()}")
    wwin32.win32_com_deinit('all')

def filter_emailinfo_by_excel(emailinfo):
    # return filter_emailinfo_by_openpyxl(emailinfo)
    return filter_emailinfo_by_xlwings(emailinfo)

